//new Date()转大写汉字日期  二〇二〇年四月十八日
function dateToChinese(date) {
    var cn = ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    var s = [];
    var YY = date.getFullYear().toString();
    for (var i = 0; i < YY.length; i++) {
        if (cn[YY.charAt(i)])
            s.push(cn[YY.charAt(i)]);
        else
            s.push(YY.charAt(i));
    }//转换年
    s.push("年");
    var MM = date.getMonth();
    if (MM < 9) {
        s.push(cn[MM + 1]);
    } else if (MM == 9) {
        s.push("十");
    } else if (MM >= 9 && MM <= 11) {
        s.push("十" + cn[MM % 10 + 1]);
    }//转换月,由于月份是从0-11,因此+1
    s.push("月");
    var DD = date.getDate();
    if (DD < 10) {
        s.push(cn[DD]);
    } else if (DD == 10) {
        s.push("十");
    } else if (DD < 20) {
        s.push("十" + cn[DD % 10]);
    } else if (DD == 20) {
        s.push("二十");
    } else if (DD < 30) {
        s.push("二十" + cn[DD % 10]);
    } else if (DD == 30) {
        s.push("三十");
    } else {
        s.push("三十" + cn[DD % 10]);
    }
    s.push("日");
    return s.join('');
}


// 合并单元格
function MergeCell(table1, startRow, endRow, col) {
    var tb = document.getElementById(table1);
    if (!tb || !tb.rows || tb.rows.length <= 0) {
        return;
    }
    if (col >= tb.rows[0].cells.length || (startRow >= endRow && endRow != 0)) {
        return;
    }
    if (endRow == 0) {
        endRow = tb.rows.length - 1;
    }
    for (var i = startRow; i < endRow; i++) {
        if (col != 0) {
            if (tb.rows[startRow].cells[col - 1].innerHTML == tb.rows[i + 1].cells[col - 1].innerHTML && tb.rows[startRow].cells[col].innerHTML == tb.rows[i + 1].cells[col].innerHTML) {
                //如果相等就合并单元格,合并之后跳过下一行
                tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[col]);
                tb.rows[startRow].cells[col].rowSpan = (tb.rows[startRow].cells[col].rowSpan) + 1;
            } else {
                MergeCell(table1, i + 1, endRow, col);
                break;
            }
        }
        else {
            if (tb.rows[startRow].cells[col].innerHTML == tb.rows[i + 1].cells[col].innerHTML) { //如果相等就合并单元格,合并之后跳过下一行
                tb.rows[i + 1].removeChild(tb.rows[i + 1].cells[col]);
                tb.rows[startRow].cells[col].rowSpan = (tb.rows[startRow].cells[col].rowSpan) + 1;
            } else {
                MergeCell(table1, i + 1, endRow, col);
                break;
            }
        }
    }

}


// 获取间隔天数
function getDays(day1, day2) {
    // 获取入参字符串形式日期的Date型日期
    var d1 = day1.getDate();
    var d2 = day2.getDate();
    // 定义一天的毫秒数
    var dayMilliSeconds = 1000 * 60 * 60 * 24;
    // 获取输入日期的毫秒数
    var d1Ms = d1.getTime();
    var d2Ms = d2.getTime();
    // 定义返回值
    var ret;
    // 对日期毫秒数进行循环比较，直到d1Ms 大于等于 d2Ms 时退出循环
    // 每次循环结束，给d1Ms 增加一天
    for (d1Ms; d1Ms <= d2Ms; d1Ms += dayMilliSeconds) {
        // 如果ret为空，则无需添加","作为分隔符
        if (!ret) {
            // 将给的毫秒数转换为Date日期
            var day = new Date(d1Ms);

            // 获取其年月日形式的字符串
            ret = day.getYMD();
        } else {

            // 否则，给ret的每个字符日期间添加","作为分隔符
            var day = new Date(d1Ms);
            ret = ret + ',' + day.getYMD();
        }
    }

    alert(ret); // 或可换为return ret;
}
// 给Date对象添加getYMD方法，获取字符串形式的年月日
Date.prototype.getYMD = function () {
    var retDate = this.getFullYear() + "-";  // 获取年份。
    retDate += this.getMonth() + 1 + "-";    // 获取月份。
    retDate += this.getDate();               // 获取日。
    return retDate;                          // 返回日期。
}
// 给String对象添加getDate方法，使字符串形式的日期返回为Date型的日期
String.prototype.getDate = function () {
    var strArr = this.split('-');
    var date = new Date(strArr[0], strArr[1] - 1, strArr[2]);
    return date;
}

// 多维数组去重
function uniq(array) {
    var obj = {},
        result = [],
        len = array.length;
    for (var i = 0; i < len; i++) {
        if (Object.prototype.toString.call(array[i]) == '[object Array]') {
            if (!obj[array[i]]) {
                obj[array[i]] = 'seat'; //seat占位 没有具体作用
                result.push(uniq(array[i])); //递归再次过滤
            }
        } else {
            if (result.indexOf(array[i]) == -1) {
                result.push(array[i]);
            }
        }
    }
    return result;
}


/**对象数组根据某一属性去重
* @param {Array} array 需要去重的数组
* @param {String} key  属性名
**/
function unique(array, key) {
    var obj = {};
    var newArray = array.reduce(function (total, current) {
        obj[current[key]] ? '' : obj[current[key]] = total.push(current);
        return total;
    }, []);
    return newArray
}


// 获取本月的结束时间和上月的开始结束时间 例 "2020-05" 输出 ["2020-05-31", "2020-04-01", "2020-04-30"]
function getDate(param) {
    var arr = [];
    // 获取年份
    var year = Number(param.split('-')[0]);
    var lastYear = year - 1;
    // 获取本月月份
    var month = Number(param.split('-')[1]);
    //上月月份
    var lastMonth = month == 1 ? 12 : month - 1;
    //本月份的结束时间
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        var endDate = param + "-31";
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        var endDate = param + "-30";
    } else if (month == 2) {
        if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {//闰年 
            var endDate = param + "-29";
        } else {
            var endDate = param + "-28";
        }
    }

    //上月份的结束时间
    if (lastMonth == 12) {
        var lastStartDate = lastYear + "-12-01";
        var lastEndDate = lastYear + "-12-31";
    } else if (lastMonth == 1 || lastMonth == 3 || lastMonth == 5 || lastMonth == 7 || lastMonth == 8) {
        var lastStartDate = year + "-0" + lastMonth + "-01";
        var lastEndDate = year + "-0" + lastMonth + "-31";
    } else if (lastMonth == 4 || lastMonth == 6 || lastMonth == 9) {
        var lastStartDate = year + "-0" + lastMonth + "-01";
        var lastEndDate = year + "-0" + lastMonth + "-30";
    } else if (lastMonth == 10) {
        var lastStartDate = year + "-10-01";
        var lastEndDate = year + "-10-31";
    } else if (lastMonth == 11) {
        var lastStartDate = year + "-11-01";
        var lastEndDate = year + "-11-30";
    } else if (lastMonth == 2) {
        var lastStartDate = year + "-02-01";
        if (((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0)) {//闰年 
            var lastEndDate = year + "-02-29";
        } else {
            var lastEndDate = year + "-02-28";
        }
    }

    arr.push(endDate);
    arr.push(lastStartDate);
    arr.push(lastEndDate);
    return arr;
}

// 去除字符串头尾空格或指定字符
function TrimString() {
    //去除字符串头尾空格或指定字符
    String.prototype.Trim = function (c) {
        if (c == null || c == "") {
            var str = this.replace(/^\s*/, '');
            var rg = /\s/;
            var i = str.length;
            while (rg.test(str.charAt(--i)));
            return str.slice(0, i + 1);
        } else {
            var rg = new RegExp("^" + c + "*");
            var str = this.replace(rg, '');
            rg = new RegExp(c);
            var i = str.length;
            while (rg.test(str.charAt(--i)));
            return str.slice(0, i + 1);
        }
    };
    //去除字符串头部空格或指定字符
    String.prototype.trimStart = function (c) {
        if (c == null || c == "") {
            var str = this.replace(/^\s*/, '');
            return str;
        } else {
            var rg = new RegExp("^" + c + "*");
            var str = this.replace(rg, '');
            return str;
        }
    };
    //去除字符串尾部空格或指定字符
    String.prototype.trimEnd = function (c) {
        if (c == null || c == "") {
            var str = this;
            var rg = /\s/;
            var i = str.length;
            while (rg.test(str.charAt(--i)));
            return str.slice(0, i + 1);
        }
        else {
            var str = this;
            var rg = new RegExp(c);
            var i = str.length;
            while (rg.test(str.charAt(--i)));
            return str.slice(0, i + 1);
        }
    }
}

// 计算今天是一年中的第几天
function DayOfYear(month, day) {
    month = parseInt(month);
    day = parseInt(day);
    var dayObj = {};
    var dayOfYear = 0;
    var yearDay = 0;
    month > 11 && (dayOfYear += 30);
    month > 10 && (dayOfYear += 31);
    month > 9 && (dayOfYear += 30);
    month > 8 && (dayOfYear += 31);
    month > 7 && (dayOfYear += 31);
    month > 6 && (dayOfYear += 30);
    month > 5 && (dayOfYear += 31);
    month > 4 && (dayOfYear += 30);
    month > 3 && (dayOfYear += 31);
    month > 2 && (dayOfYear += (year % 400 == 0 && year % 100 != 0 || year % 4 == 0) ? 29 : 28);
    month > 1 && (dayOfYear += 31);
    dayOfYear += day - 1;
    yearDay = (year % 400 == 0 && year % 100 != 0 || year % 4 == 0) ? 366 : 365;
    dayObj.dayOfYear = dayOfYear;
    dayObj.yearDay = yearDay;
    dayObj.residueDay = yearDay - dayOfYear;
    return dayObj;
}


// 判断当前时间为第几周
function theWeek() {
    var totalDays = 0;
    now = new Date();
    years = now.getYear();
    if (years < 1000)
        years += 1900;
    var days = new Array(12);
    days[0] = 31;
    days[2] = 31;
    days[3] = 30;
    days[4] = 31;
    days[5] = 30;
    days[6] = 31;
    days[7] = 31;
    days[8] = 30;
    days[9] = 31;
    days[10] = 30;
    days[11] = 31;

    //判断是否为闰年，针对2月的天数进行计算
    if (Math.round(now.getYear() / 4) == now.getYear() / 4) {
        days[1] = 29
    } else {
        days[1] = 28
    }

    if (now.getMonth() == 0) {
        totalDays = totalDays + now.getDate();
    } else {
        var curMonth = now.getMonth();
        for (var count = 1; count <= curMonth; count++) {
            totalDays = totalDays + days[count - 1];
        }
        totalDays = totalDays + now.getDate();
    }
    //得到第几周
    var week = Math.ceil(totalDays / 7);
    return week;
}


/**修改数组或对象的key
 * @param {Array} list 数组或对象
 * @param {Object} map 映射 如将xingming改为name {xingming:'name'}
 **/
function transitionKey(list, map) {
    function toTransition(list) {
        var newObj = list.constructor === Array ? [] : {};
        for (var key in list) {
            var newKey = map[key] ? map[key] : key;
            newObj[newKey] = typeof list[key] === 'object' ? toTransition(list[key], map) : list[key];
        }
        return newObj;
    }

    return toTransition(list);
}


/**获取某年第几周的开始日期和结束日期
 * 如: ('2020',1) 返回 ['2019-12-30','2020-01-05']
 * @param {String} year 年份
 * @param {Number} week 第几周
   **/
function getWeekDate(year, week) {
    //获取周开始日期
    var getWeekStartDate = function (year, week) {
        // Thursday in current week decides the year.
        var date = new Date(year, 0, 4);
        date.setDate(date.getDate() - (date.getDay() + 6) % 7);
        date.setTime(date.getTime() + 7 * 86400000 * (week - 1));
        var year = date.getFullYear();
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var dates = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
        return year + '-' + month + '-' + dates;
    };

    //获取周结束日期
    var getWeekEndDate = function (year, week) {
        // Thursday in current week decides the year.
        var date = new Date(year, 0, 4);
        date.setDate(date.getDate() - (date.getDay() + 6) % 7);
        date.setTime(date.getTime() + (7 * 86400000 * week) - 1);
        var year = date.getFullYear();
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var dates = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
        return year + '-' + month + '-' + dates;
    };
    return [getWeekStartDate(year, week), getWeekEndDate(year, week)];
}


/**获取某年总共的周数
 * @param {String} year 年份
   **/
function getWeekOfYear(year) {
    var totalDay;//一年的天数
    var totalWeek = 0;//一年的周数
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        totalDay = 366;
    } else {
        totalDay = 365;
    }
    var startDay = new Date(year).getDay();  //这一年的第一天为周几
    startDay == 0 ? startDay = 7 : true;
    // console.log('startDay',startDay);
    if (startDay <= 4) {
        totalWeek += 1;
    } else {
        totalWeek += 0;
    }
    var endDay = new Date(year, '11', '31').getDay();  //这一年的最后一天为周几
    // console.log('endDay',endDay);
    var week = (totalDay - (7 - startDay + 1) - endDay) / 7;
    // console.log("week",week);
    if (endDay <= 3) {
        totalWeek += week;
    } else {
        totalWeek += week + 1;
    }
    return totalWeek;
}


// 根据开始时间和结束时间获取日期数组
function getDateArr(startDate, endDate) {
    var dateArr = [];
    var startTime = new Date(startDate).getTime();
    var endTime = new Date(endDate).getTime();
    var year, month, day, date;
    for (var i = startTime; i <= endTime; i += 86400000) {
        year = new Date(i).getFullYear();
        month = new Date(i).getMonth() + 1 < 10 ? '0' + (new Date(i).getMonth() + 1) : (new Date(i).getMonth() + 1);
        day = new Date(i).getDate() < 10 ? '0' + new Date(i).getDate() : new Date(i).getDate();
        date = year + '-' + month + '-' + day;
        dateArr.push(date);
    }
    return dateArr;
}

// 密码校验 var password = '111AAAAa';
function checkPassword(str) {
    var num = password.length;
    var errorCode = /^[a-zA-Z0-9_]{6,16}$/;
    var correctCode = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).{6,16}$/;
    //var reg = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])).{8,20}$/; //比上面的多了特殊字符
    if (num < 6 || num > 16 || num < 0) {
        console.log('密码长度为6-16个字符');
    } else if (!errorCode.test(password)) {
        console.log('密码只能由字母、数字、下划线组成');
    } else if (!correctCode.test(password)) {
        console.log('密码必须同时包含大写字母、小写字母和数字');
    } else {
        console.log('密码格式正确');
    }
}


// 嵌套数组递归为一维数组
//tempArr 用于存放展开后的一维数组
//data 嵌套数组
function spreadArray(tempArr, data) {
    $.each(data, function (index, value) {
        tempArr.push(value);
        if (value.children && value.children.length > 0) {
            var children = value.children;
            delete value.children;
            spreadArray(tempArr, children);
        }
    })
    return tempArr;
}


// 过滤树
function treeFilter(tree, func) {
    return tree.map(node => ({ ...node })).filter(node => {
        node.children = node.children && treeFilter(node.children, func)
        return func(node) || (node.children && node.children.length)
    })
}

let tree = [{
    id: '1',
    parentId: '0',
    name: '郑州市',
    age: 80,
    children: [
        {
            id: '1-1',
            parentId: '0',
            name: '荥阳市',
            age: 70
        },
        {
            id: '1-2',
            parentId: '0',
            name: '开封市',
            age: 10
        },
    ]
}]
let result = treeFilter(tree, node => {
    return node.age < 18;
})


// 获取url参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) {
        return r[2];
    } else {
        return null;
    }
}